package com.itic.system.carrage.template.service;

import java.util.ArrayList;
import java.util.List;

import com.itic.appbase.framework.type.DeliveryMethod;
import com.itic.appbase.framework.type.RegionLevel;
import com.itic.system.carrage.templateRegion.persistence.model.CarrageTemplateRegion;
import com.itic.system.region.persistence.model.HppRegion;
import com.itic.system.region.service.HppRegionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.system.carrage.template.persistence.dao.CarrageTemplateDao;
import com.itic.system.carrage.template.persistence.model.CarrageTemplate;
import com.itic.system.carrage.template.persistence.model.CarrageTemplateExample;
import com.itic.system.carrage.template.persistence.model.CarrageTemplateExample.Criteria;
import com.itic.system.vo.CarrageEditVo;
import com.itic.system.vo.CarrageVo;
import com.itic.system.vo.TemplateContVo;
import com.itic.system.carrage.templatePiece.persistence.model.CarrageTemplatePiece;
import com.itic.system.carrage.templatePiece.service.CarrageTemplatePieceService;
import com.itic.system.carrage.templateRegion.persistence.model.Condition;
import com.itic.system.carrage.templateRegion.service.CarrageTemplateRegionService;
import com.itic.system.carrage.templatePiece.persistence.dao.CarrageTemplatePieceDao;
import com.itic.system.carrage.templateRegion.persistence.dao.CarrageTemplateRegionDao;
import com.itic.system.user.user.persistence.model.HppUser;
import com.itic.system.user.user.service.HppUserService;

@Service
@Transactional
public class CarrageTemplateService
     extends CrudService<CarrageTemplateDao,CarrageTemplate,CarrageTemplateExample> {
    @Autowired
    private CarrageTemplateDao carrageTemplateDao;
    @Autowired
    private CarrageTemplatePieceService carrageTemplatePieceService;
    @Autowired
    private CarrageTemplateRegionService carrageTemplateRegionService;
    @Autowired
    private CarrageTemplatePieceDao carrageTemplatePieceDao;
    @Autowired
    private CarrageTemplateRegionDao carrageTemplateRegionDao;
    @Autowired 
    private HppUserService hppUserService;
    @Autowired
	private HppRegionService hppRegionService;
    
    /**
     * 添加默认模板
     * @param userId
     */
    public void createDefaultTemplate(String userId){
    	if(StringUtils.isNotBlank(userId)){
    		HppUser hppUser = hppUserService.get(userId);
    		if(hppUser != null){
    			CarrageTemplate template = new CarrageTemplate();
    			String id = IdGen.uuid();
    			template.setId(id);
    			template.setName("全国包邮");
    			template.setUserId(userId);
    			this.add(template);
    			CarrageTemplatePiece piece = new CarrageTemplatePiece();
    			piece.setAddPieceCount(1);
    			piece.setAddPieceFee(0.0);
    			piece.setCarrageTemplateId(id);
    			piece.setFirstPieceCount(1);
    			piece.setFirstPieceFee(0.0);
    			carrageTemplatePieceService.add(piece);
    		}
    	}
    }
    /**
     * 编辑模板信息
     * @param userId
     * @param templateId
     * @param list
     * @return
     */
    public String editCarrageTemplate(String userId,String templateId,String tempName,List<CarrageEditVo> list){
    	String result = FAILED;
    	CarrageTemplate template = this.get(templateId);
    	if(template != null){
    		template.setName(tempName);
    		this.edit(template);
    		//先删除piece和region再重新生成
        	this.carrageTemplatePieceDao.delBytemplateId(templateId);
        	this.carrageTemplateRegionDao.delBytemplateId(templateId);
        	//生成,有pieceID的，没有pieceid的相当于新增
        	for(CarrageEditVo editvo:list){
        		String[] regionIds = editvo.getRegionIds();
        		String pieceId = editvo.getPieceId();
        		CarrageTemplatePiece piece = new CarrageTemplatePiece();
    			piece.setAddPieceCount(editvo.getAddPcount());
				piece.setAddPieceFee(editvo.getAddTeranfee());
				piece.setCarrageTemplateId(templateId);
				piece.setFirstPieceCount(editvo.getFirstPcount());
				piece.setFirstPieceFee(editvo.getFirstTranfee());
				piece.setIsDefault(editvo.getIsDefault());
        		if(StringUtils.isNotBlank(pieceId)){
					piece.setId(pieceId);
					carrageTemplatePieceService.add(piece);
					result = carrageTemplateRegionService.add(templateId, pieceId, regionIds);
        		}else{
        			String pId = IdGen.uuid();
        			piece.setId(pId);
        			carrageTemplatePieceService.add(piece);
        			String isDefault = editvo.getIsDefault();
        			if(isDefault.equals(DBConst.FALSE)){
            			result = carrageTemplateRegionService.add(templateId, pId, regionIds);
        			}
        		}
        	}
    	}
    	return result;
    }
    /**
     * 校验操作权限
     * @param userId
     * @param templateId
     * @return
     */
    public Boolean isOwn(String userId,String templateId){
    	Boolean isOwn = false;
    	CarrageTemplateExample example = new CarrageTemplateExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	criteria.andIdEqualTo(templateId);
    	List<CarrageTemplate> list = this.list(example);
    	if(list.size()>0){
    		isOwn = true;
    	}
    	return isOwn;
    }
    public void delCarrageTemplate(String userId,String templateId){
    	String result = FAILED;
    	if(StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(templateId)){
    		//删除模板
    		Condition condition = new Condition();
    		condition.setUserId(userId);
    		condition.setTemplateId(templateId);
    		this.carrageTemplateDao.deleteTemplate(condition);
    		//删除piece
    		this.carrageTemplatePieceDao.delBytemplateId(templateId);
    		//删除区域数据
    		this.carrageTemplateRegionDao.delBytemplateId(templateId);
    	}
    }
    /**
     * 根据用户Id获取所有运费模板列表
     * @param userId
     * @return
     */
    public List<CarrageVo> gettemplateList(CarrageTemplateExample example,String userId){
    	List<CarrageTemplate> templateList = this.getlistByUserId(example, userId);
		List<CarrageVo> list = new ArrayList<CarrageVo>();
		if (templateList.size() > 0) {
			for (CarrageTemplate template : templateList) {
				String templateId = template.getId();
				String tempName = template.getName();
				List<CarrageTemplatePiece> pieceList = carrageTemplatePieceService.getBytemplateId(templateId);
				for (CarrageTemplatePiece piece : pieceList) {
					String pieceId = piece.getId();
					Condition condition = new Condition();
					condition.setPieceId(pieceId);
					condition.setTemplateId(templateId);
					List<String> regionList = carrageTemplateRegionService.getBypieceId(condition);
					String regionName = carrageTemplateRegionService.getRegionName(condition);
					CarrageVo vo = new CarrageVo();
					vo.setAddPcount(piece.getAddPieceCount());
					vo.setAddTeranfee(piece.getAddPieceFee());
					vo.setFirstPcount(piece.getFirstPieceCount());
					vo.setFirstTranfee(piece.getFirstPieceFee());
					vo.setIsDefault(piece.getIsDefault());
					vo.setPieceId(pieceId);
					vo.setRegionIds(regionList);
					vo.setTemplateId(templateId);
					vo.setTempName(tempName);
					if (piece.getIsDefault().equals(DBConst.TRUE)) {
						vo.setRegionName("中国");
					} else {
						vo.setRegionName(regionName);
					}
					list.add(vo);
				}
			}
		}
		return list;
    } 
    /**
     * 运费模板-区域表添加
     * @param userId
     * @param name
     * @param templateId
     * @param volist
     * @return
     */
    public String addCarrageTemplate(String userId,String name,String templateId,List<TemplateContVo> volist){
    	String result = FAILED;
    	result = this.add(userId, name, templateId);
		if (ResponseCode.SUCCESS.getCode().equals(result)) {
			for (TemplateContVo vo : volist) {
				Integer firstPcount = vo.getFirstPcount();
				Double firstTranfee = vo.getFirstTranfee();
				Integer addPcount = vo.getAddPcount();
				Double addTranfee = vo.getAddTeranfee();
				String isDefault = vo.getIsDefault();
				String pId = IdGen.uuid();
				result = carrageTemplatePieceService.add(templateId, pId, isDefault, firstPcount,
						firstTranfee, addPcount, addTranfee);
				if (ResponseCode.SUCCESS.getCode().equals(result) && DBConst.FALSE.equals(isDefault)) {
					String[] regionIds = vo.getRegionIds();
					result = carrageTemplateRegionService.add(templateId, pId, regionIds);
					
				}
			}
		}
		return result;
    }
    
    
    /**
     * 添加新模板
     * @param name
     * @param id
     * @return
     */
    public String add(String userId,String name,String id){
    	String result = FAILED;
    	if(StringHelper.isNotBlank(name) && StringHelper.isNotBlank(id)){
    		CarrageTemplate template = new CarrageTemplate();
    		template.setId(id);
    		template.setName(name);
    		template.setUserId(userId);
    		result = this.add(template);
    	}
    	return result;
    }
    /**
     * 用户id获取模板列表
     * @param userId
     * @return
     */
    public List<CarrageTemplate> getlistByUserId(String userId){
    	List<CarrageTemplate> list = this.carrageTemplateDao.getlist(userId);
    	return list;
    }
    
    public List<CarrageTemplate> getlistByUserId(CarrageTemplateExample example,String userId){
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	List<CarrageTemplate> list = this.carrageTemplateDao.selectByExample(example);
    	return list;
    }

	/**
	 * 计算不同运费模板 不同地区的运费
	 * @param templateId
	 * @param regionId
	 * @param count
	 * @return
	 */
    public double  calFeeByTemplateAndRegionId(String templateId,String regionId,int count){
		double fee = 0.0;
    	//运费模板
    	CarrageTemplate carrageTemplate = this.get(templateId);
		//全国包邮模板  其他模板 判断 是否是默认
		HppRegion region = this.hppRegionService.get(regionId);
		String templatePieceId = null;
		if(carrageTemplate !=null && region!=null){
			//查看该地区是否含有省市区 的首费 以及续费
			CarrageTemplateRegion templateRegion = this.carrageTemplateRegionService.recurCarrageTemplateRegion(templateId,regionId);
			if(templateRegion!=null)
				templatePieceId =templateRegion.getPieceId();
		}
		//计算运费
		if(templatePieceId !=null)
			fee = this.carrageTemplatePieceService.calFeeByTemplatePiectIdAndCount(templatePieceId,count);
    	return fee;
	}

	/**
	 * 计算不同发货类型的运费
	 * @param deliveryMethod
	 * @param templateId
	 * @param regionId
	 * @param count
	 * @return
	 */
	public double calFeeByDeliveryMethod(DeliveryMethod deliveryMethod,String templateId,String regionId,int count){
		double fee = 0 ;
    	switch (deliveryMethod){
			case Delivery:
				if(StringUtils.isNotEmpty(regionId))
					fee = calFeeByTemplateAndRegionId(templateId,regionId,count);
				break;
			case Self:
			case QCode:
			case VirtualCode:
				break;
		}
		return fee;
	}

}